package servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.UserAttr;

import util.Helper;

abstract public class ServletTemplate extends HttpServlet{
    /**
     * 默认的编号
     */
    protected static final long serialVersionUID = 1L;
    protected static final String defEncode = "utf-8";
    
    protected HttpServletRequest _request;
    protected HttpServletResponse _response;
    
    /**
     * 构造函数 
     */
    public ServletTemplate() {
        super();
    }
    
    /**
     * 初始化 
     */
    public void init(ServletConfig config) throws ServletException{
        super.init(config);
        
        this._request   = null;
        this._response  = null;
    }
    
    /**
     * 服务操作 
     */
    public void service(HttpServletRequest request,
                          HttpServletResponse response) throws IOException, ServletException{
        super.service(request, response);
    }
  
    
    /**
     * 执行POST操作 
     */
    public void doPost(HttpServletRequest request,
                                  HttpServletResponse response) throws IOException, ServletException {
        this.setRequestResponse(request, response);
        this.setCharset();
    }
   
    /**
     * 执行Get提交操作 
     */
    public void doGet(HttpServletRequest request,
                        HttpServletResponse response) throws IOException, ServletException{
        this.doPost(request, response);
    }
   
    /**
     * 设置请求及反馈的编码 
     */
    protected void setCharset(String encode) {
        try {
            this._response.setContentType("text/html;charset=" + encode);
            this._request.setCharacterEncoding(encode);
        } catch(Exception ex) {
            //some code
            System.out.println("Not support encoding " + encode);
        }
    }
   
    /**
     * 设置请求反馈的字符编码的重载
     *  
     */
    protected void setCharset() {
       this.setCharset(ServletTemplate.defEncode); 
    }
   
    /**
     * 设置请求返回对象 
     */
    protected void setRequestResponse(HttpServletRequest request,
            HttpServletResponse response) {
        this._request   = request;
        this._response  = response;
    }
   
    /**
     *  设置request的属性
     */
    protected void setRequestAttr(String name, Object value) {
        this._request.setAttribute(name, value);
    }
   
    /**
     * 得到request的属性 
     */
    protected Object getRequestAttr(String name) {
        return this._request.getAttribute(name);
    }
   
    /**
     * 得到请求的变量 
     */
    protected Object getRequestParam(String name) {
        return this._request.getParameter(name);
    }
   
    /**
     * 得到Session对象值 
     */
    protected Object getSessionAttr(String name) {
        return this._request.getSession().getAttribute(name);
    }
   
    /**
     * 设置Session属性 
     */
    protected void setSessionAttr(String name, Object value) {
        this._request.getSession().setAttribute(name, value);
    }
   
    /**
     * 重定向到一个新的链接，request数据不可用 
     */
    protected void redirect(String url) {
        try {
            this._response.sendRedirect(url);
        } catch(IOException ex) {
            try {
                this._response.sendRedirect("/index");
            } catch(IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
   
    /**
     * 重定向一个已知的Servlet位置，可以用request,response对象 
     */
    protected void forward(String url) {
        try {
            this._request.getRequestDispatcher(url).forward(this._request, this._response);
        } catch(Exception ex) {
            try {
                this._request.getRequestDispatcher("/index").forward(this._request, this._response);
            } catch(Exception e) {
                System.out.println(e.getMessage()); 
            }
        }
    }
   
    /**
     * 用户是否登陆 
     */
    protected boolean isLogin() {
        Object validTime    = this.getSessionAttr("validTime");
        if(validTime == null) {
            return false;
        }
        long nowTimeStamp   = Helper.getTimeStamp();
        long subResult      =  Long.parseLong(validTime.toString()) - nowTimeStamp;
        System.out.println(subResult);
        if(validTime == null || subResult < 0) {
            return false;
        }
        Object objUserAttr   = this.getSessionAttr("userAttr");
        if(objUserAttr == null) {
            return false;
        }
        System.out.println("User yes..");
        
        return true;
    }
   
    /**
     * 检测是否为管理员 
     */
    protected boolean isAdmin() {
        Object objUserAttr   = this.getSessionAttr("userAttr");
        if(objUserAttr == null) {
            return false;
        }
        UserAttr userAttr   = (UserAttr)objUserAttr;
        int userType        = userAttr.getUserType();
        System.out.println(userType);
        if(userType != 1) {
            return false;
        }
        
        return true;
    }
   
    /**
     * 是否为自己 
     */
    protected boolean isSelf(int userId) {
        Object objUserAttr   = this.getSessionAttr("userAttr");
        if(objUserAttr == null) {
            return true;
        }
        UserAttr userAttr   = (UserAttr)objUserAttr;
        if(userId != userAttr.getUserId()) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 释放对象 
     */
    public void destroy () {
        this._request   = null;
        this._response  = null;
    }
    
}
